﻿using GatewayClient.MQ;
using Models.Common;
using Models.Device;
using Newtonsoft.Json;
using RabbitMQ.Client;
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Threading;
using UtilsBase;

namespace GatewayClient.Service
{
    public class ServiceUpGratdeConfig
    {

        /// </summary>
        /// <summary>
        /// 更新接口地址
        /// </summary>
        public void mqInfoSet(MQReqModel<object> mQReqModel)
        {
            try
            {
                MQTTInfo mQTTInfo = UtilsObject.DynamicToEntity<MQTTInfo>(mQReqModel.data);
                //定时更新
                Console.WriteLine("开始更新appsetting，请等候");

                UtilsAppsetting.WriteSettings("mqtt", "mqUserName", mQTTInfo.UserName);
                Thread.Sleep(1000);
                UtilsAppsetting.WriteSettings("mqtt", "mqPassword", mQTTInfo.Password);
                Thread.Sleep(1000);
                UtilsAppsetting.WriteSettings("mqtt", "mqHostName", mQTTInfo.HostName);
                Thread.Sleep(1000);
                UtilsAppsetting.WriteSettings("mqtt", "mqPort", mQTTInfo.Port.ToString());
                Thread.Sleep(1000);
                UtilsAppsetting.WriteSettings("mqtt", "mqVirtualHost", mQTTInfo.VirtualHost);
                Thread.Sleep(1000);
                Console.WriteLine("更新appsetting 完成");
                mQReqModel.respMsg = "成功";
                new ServiceMQ_Helper().sendMsg(mQReqModel);
            }
            catch (Exception ex)
            {
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = "失败" + ex.Message;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine("更新报错");
                // new UtilsFileHelper().log_WriteMessageAppend("error", "" + ex.ToString());
                Console.WriteLine(ex);
            }
        }


        /// </summary>
        /// <summary>
        /// 更新接口地址
        /// </summary>
        public void updateConfig(MQReqModel<object> mQReqModel)
        {
            try
            {
                ModelConfigKeyValue modelConfig = UtilsObject.DynamicToEntity<ModelConfigKeyValue>(mQReqModel.data);

                UtilsAppsetting.WriteSettings(modelConfig.root, modelConfig.name, modelConfig.value);
                Console.WriteLine("更新appsetting 完成");

                mQReqModel.respMsg = "成功";
                new ServiceMQ_Helper().sendMsg(mQReqModel);
            }
            catch (Exception ex)
            {
                mQReqModel.respCode = ResponseCode.System_ERROR;
                mQReqModel.respMsg = "失败" + ex.Message;
                new ServiceMQ_Helper().sendMsg(mQReqModel);
                Console.WriteLine("更新报错");
                //new UtilsFileHelper().log_WriteMessageAppend("error", "" + ex.ToString());
                Console.WriteLine(ex);
            }
        }

    }
}
